    <!-- 专项债券项目储备申报列表 -->
<template>
  <RkContainer :isFooter="false">
    <template #header_left>
      <RkButtonGroup :options="json_jb_button"
        v-model="queryParams.wfStatus"
        @click="handleSearch" />
    </template>
    <template #header_right>
      <el-button v-if="queryParams.wfStatus=='001'"
        @click="handelAdd">新增项目</el-button>
      <el-button v-if="queryParams.wfStatus=='001' || queryParams.wfStatus=='004'"
        @click="handleOpenRecord('edit', '修改')">修改</el-button>
      <el-button v-if="queryParams.wfStatus=='001' || queryParams.wfStatus=='004'"
        type="danger"
        @click="handleOperation('delete', '删除')">删除</el-button>
      <el-button v-if="queryParams.wfStatus=='001' || queryParams.wfStatus=='004'"
        type="primary"
        @click="handleOperation('send','送审')">送审</el-button>
      <el-button v-if="queryParams.wfStatus=='002'"
        type="danger"
        @click="handleOperation('cancel','撤销审核')">撤销送审</el-button>
      <el-button @click="handleOpenRecord('rocord', '操作记录')">操作记录</el-button>
    </template>
    <template #aside>
      <rk-ad-ag-tree layoutTree="ag"
        :agConfig="{
          code:'2300',
        }"
        @agNodeClick="handleAgNodeClick">
      </rk-ad-ag-tree>
    </template>
    <template #main>
      <rk-condition>
        <template #content>
          <rk-grid ref="grProjApply"
            title="专项债券储备信息表"
            dataUrl="/proResApply/reserveProjectPage"
            boxConfig
            :params="queryParams"
            :columns="tableColumns"
            :footerConfig="{
              showFooter:true,
              footerParams:['applyAmt','proCapital','totalBudget']
            }">
            <template #toolbar_title_buttons>
              <el-select v-model="queryParams.dw"
                placeholder="请选择单位"
                class="mr-15px w-80px"
                clearable
                @change="handleSearch">
                <el-option v-for="item in COMMON_AMOUNT_UNIT.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value" />
              </el-select>
              <el-input v-model="queryParams.mhcx"
                placeholder="请输入申报单位/项目名称"
                class="mr-15px w-200px"
                @input="handleSearch"
                clearable>
              </el-input>
            </template>
            <template #bondType="{ row }">
              <span class="mx-1">
                {{ COMMON_BOND_TYPES.options[row.bondTypeCode].echo }}
              </span>
            </template>
          </rk-grid>
        </template>
      </rk-condition>
    </template>
  </RkContainer>
  <OperationLog ref="OperationLogRef" />
  <ReserveProjDialog
    ref="reserveSpecialProjDialogRef"
    type="special"
    :formId="formId"
    :processKey="processKey"
    @refresh="handleSearch"
  />
</template>
<script setup lang="jsx">
import OperationLog from '@/components/log/OperationLog.vue'
import ReserveProjDialog from '@/components/form/business/ReserveProjDialog.vue'
import { RkConfirmBox } from '@/components/message-box/index.js'
import { json_jb_button } from '@/common/button-data.js'
import { WF_TASK_SEND_AUDIT, WF_TASK_CANCEL } from '@/common/cons-common.js'
import { COMMON_BOND_TYPES, COMMON_AMOUNT_UNIT } from '@/enums/enums-common.js'
import { deleteReserveProject, reserveProHandleTask } from '@/api/api-project'


// 流程标识
const processKey = ref('PRO_CBK')

const { appContext } = getCurrentInstance()
const globalProxy = appContext.config.globalProperties

let leaf = ref(false)
// 查询参数
let queryParams = reactive({
  wfStatus: '001',
  status: undefined,
  mhcx: undefined,
  bondTypeCode: 2,    // 债券类型测试数据 1、一般 2、专项
  nodeId: undefined,  //填报测试数据
  processKey: 'PRO_CBK', //测试数据
  adCode: '2300', //'321005'
  agCode: undefined,
  agId: undefined,
  dw: 2
})
// 从当前路由中获取数据
let route = useRoute()
const query = route.query
queryParams.nodeId = query.nodeId

// 表格的模板引用
const grProjApply = ref('')
// 表格字段定义
const tableColumns = ref([
  { field: 'agencyName', title: '申报单位', width: 180, },
  {
    field: 'proName', title: '项目名称', width: 250, align: 'left',
    slots: {
      default: ({ row }) => {
        const title = row.proName || ''
        return title ? [
          <a
            class='yhs-pro-name'
            target='_blank'
            rel='noopener'
            href={`/proj-yhs?proId=${row.proId}&type=sp`}>{title}</a>
        ] : ''
      }
    }
  },
  { field: 'proCode', title: '项目编码', width: 130, },
  { field: 'fiscalYear', title: '年度', width: 120, },
  { field: 'debtDeadlineName', title: '债券期限', width: 150 },
  { field: 'applyAmt', title: '申请金额', width: 200, align: 'right', formatter: 'formatThousand' },
  {
    field: 'expFuncName', title: '支出功能分类', width: 200
  },
  {
    field: 'govBgtEcoName', title: '政府预算支出经济分类', width: 200
  },
  {
    field: 'depBgtEcoName', title: '部门预算支出经济分类', width: 200
  },
  { field: 'proCapital', title: '项目资本金', width: 200, align: 'right', formatter: 'formatThousand' },
  { field: 'bondTypeCode', title: '申请类型', width: 150, slots: { default: 'bondType' } },
  { field: 'applyDate', title: '申报日期', width: 200, },
  { field: 'setupYear', title: '立项年度', width: 180 },
  { field: 'proTypeName', title: '项目类型', width: 150 },
  { field: 'fundInvestAreaCode', title: '资金投向领域', width: 250 },
  { field: 'totalBudget', title: '项目总概算', width: 200, align: 'right', formatter: 'formatThousand' },
  { field: 'proStatusName', title: '建设状态', width: 150 },
  { field: 'startDate', title: '开工日期', width: 150 },
  { field: 'endDate', title: '竣工日期', width: 150 },
  { field: 'remark', title: '备注', width: 120 },
])

/**
 * 左侧单位树点击事件，刷新主页面表格
 */
const handleAgNodeClick = ({ data }) => {
  queryParams.agCode = data.code
  queryParams.agId = data.id
  leaf.value = data.leaf
  baseInfo.agId = data.id
  baseInfo.agCode = data.code
  baseInfo.agName = data.name
  baseInfo.agParentId = data.parentId
  handleSearch();
}

/**查询 */
const handleSearch = () => {
  grProjApply.value.searchEvent()
}
//送审、撤销送审、删除
const handleOperation = async (buttonType, textName) => {
  const seleRows = grProjApply.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows) {
    globalProxy.$message({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
    return;
  }
  //获取选中数据
  const ProId = []
  const TaskId = []
  const ApplyId = []
  seleRows.forEach(element => {
    ApplyId.push(element.applyId)
    ProId.push(element.proId)
    TaskId.push(element.taskId)
  });
  const applyIds = ApplyId.join(',')
  const proIds = ProId.join(',')
  const taskIds = TaskId.join(',')
  if (buttonType == 'send') { //送审
    const deleteParams = { applyIds, taskIds, proIds, bondTypeCode: 2, nodeId: queryParams.nodeId, taskType: WF_TASK_SEND_AUDIT.value }
    const result = await reserveProHandleTask(deleteParams)
    const { data, code, msg } = result
    if (code === 200) {
      globalProxy.$message({ message: `${textName}成功！`, type: "success" });
      handleSearch()
    } else {
      globalProxy.$message({ message: `${msg}`, type: "error" });
    }
  } else if (buttonType == 'cancel') { //撤销送审
    const deleteParams = { applyIds, taskIds, proIds, nodeId: queryParams.nodeId, taskType: WF_TASK_CANCEL.value }
    const result = await reserveProHandleTask(deleteParams)
    const { data, code, msg } = result
    if (code === 200) {
      globalProxy.$message({ message: `${textName}成功！`, type: "success" });
      handleSearch()
    } else {
      globalProxy.$message({ message: `${msg}`, type: "error" });
    }
  } else { //删除
    RkConfirmBox({
      title: '提示',
      content: `您确定要${textName}吗？`,
      onSubmit: async function () {
        const deleteParams = { proIds, applyIds }
        const result = await deleteReserveProject(deleteParams)
        const { data, code, msg } = result
        if (code === 200) {
          globalProxy.$message({ message: `${textName}成功！`, type: "success" });
          handleSearch();
        } else {
          globalProxy.$message({ message: `${msg}`, type: "error" });
        }
      },
      onCancel: function () {
      }
    })
  }
}
// 操作记录模板引用
const OperationLogRef = ref(null)
const handleOpenRecord = (buttonType, textName) => {
  const seleRows = grProjApply.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows || seleRows.length > 1) {
    globalProxy.$message({ message: "请选择一条数据！", type: "warning" });
    return;
  }
  //修改
  if (buttonType == 'edit') {
    handleEditProj(seleRows[0].proId)
  }
  //操作记录
  else {
    let applyId = ''
    seleRows.forEach(element => {
      applyId = element.applyId
    });
    OperationLogRef.value.handleOpen(applyId)
  }
}

//新增项目
const handelAdd = () => {
  if (!leaf.value) {
    globalProxy.$message({ message: '请先选择单位再进行操作！', type: "warning" });
    return;
  }
  handleAddProj()
}

// ----- 专项项目填报示例
// 专项项目表单ID
const formId = ref(query.formId || '')
// 项目申报基本信息
const baseInfo = reactive({
  // 选中项目ID
  proId: '',
  // 选中区划编码
  adCode: '2300',
  // 单位ID
  agId: '',
  // 选中单位编码
  agCode: '',
  // 单位名称
  agName: '',
  // 上级单位Id
  agParentId: ''
})
// 项目添加面板模板引用
const reserveSpecialProjDialogRef = ref()
/** 添加项目 */
const handleAddProj = () => {
  const addInfo = toRaw(baseInfo)
  reserveSpecialProjDialogRef.value.handleAdd(addInfo);
}
/** 修改项目 */
const handleEditProj = (id) => {
  const editInfo = toRaw(baseInfo)
  editInfo.proId = id
  reserveSpecialProjDialogRef.value.handleEdit(editInfo)
}

</script>

<style lang="scss" scoped>
.mr-15px {
  margin-right: 15px;
  &:last-child {
    margin-right: 0;
  }
}
.w-200px {
  width: 200px;
}
</style>
